import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Message } from 'element-ui'
import { getRouters } from "@/api/login";
import { tokenLocalStorage } from '@/utils/request'



Vue.use(VueRouter)


const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login.vue'),
    meta: {
      requireLogin: false
    },
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('@/layout/index.vue'),
    children:[]
  }
]

let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(this, location, () => { }, () => { })
  }
}

const router = new VueRouter({
  routes
})

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}


// 路由拦截
router.beforeEach(async (to, from, next) => {
  //判断是否需要登录
  if (to.meta.requireLogin !== false) {
    //  页面需要登录后访问
    let token = tokenLocalStorage;
    if (token) {
      if(store.state.permission.treeData && store.state.permission.treeData != 0){
        next();
      }
      let { data } = await getRouters();
      store.commit("permission/setTreeData", data);
      let result = []
      buildRouter(store.state.permission.treeData, result)
      let dynamicRoutes = [];
      result.forEach(item => {
        dynamicRoutes = dynamicRoutes.concat(item)
      })
      let newRoutes = router.options.routes
      newRoutes.forEach(item => {
        if(item.name === 'index'){
          item.children = dynamicRoutes;
          return;
        }
      })
      router.addRoutes(newRoutes)
      next(to.path) // 表示已经登录
    } else {
      next({ name: 'login' })
    }
  } else {
    // buildRouter(store.state.permission.treeData, dynamicRoutes)
    // console.log(dynamicRoutes)
    next()
  }
})

function buildRouter(treeData, result) {
  treeData.forEach(item => {
    let temp = []
    if (item.type === '0') {
      buildRouter(item.children, temp)
      result.push(temp)
    }
    else if (item.type === '1') {
      result.push({
        path: item.path,
        component: () => import('@/views/' + item.component),
      })
    }
  })
}






export default router
